#include<iostream>
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
using namespace std;

//管道特性：
//1.当缓冲区满了，写端阻塞
//2.当缓冲区空了，读端阻塞
//3.读端关闭，写端立马收到信号终止进程
//4.写端关闭，一直读，直到返回0

int main()
{
    int pipefd[2]={0};
    pipe(pipefd);

    //父进程写，子进程读
    pid_t ret=fork(); 
    if(ret==-1)
    {
        cout<<"子进程创建失败"<<endl;
    }
    else if(ret==0)
    {
        //子进程
        close(pipefd[1]);
        //读取
        while(true)
        {
            char buf[1024]={0};
            int n=read(pipefd[0],buf,1023);
            cout<<"child recv message "<<n<<" bytes: "<<buf<<endl;

            close(pipefd[0]);
            sleep(100);
        }
        exit(0);
    }
    close(pipefd[0]);
    //写入
    while(1)
    {
        sleep(1);
        char buf[1024]={0};
        snprintf(buf,1024,"hello child ,i am father");
        int n=write(pipefd[1],buf,strlen(buf));
        cout<<"write "<<n<<"bytes"<<endl;
    }
    return 0;
}